package com.jzoom.zoom.admin.models;

import com.jzoom.zoom.common.filter.Filter;
import com.jzoom.zoom.common.filter.pattern.PatternFilterFactory;
import com.jzoom.zoom.common.io.Io;
import com.jzoom.zoom.common.utils.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class FileExplorerService {

    public String getContent(File file) throws IOException {

        return Io.readString(file, "utf-8");
    }

    public void saveContent(File file, String content) throws IOException {
        Io.writeString(file, content);
    }

    public static class FileInfo{
        private String name;
        private long lastModified;
        private boolean file;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public long getLastModified() {
            return lastModified;
        }

        public void setLastModified(long lastModified) {
            this.lastModified = lastModified;
        }

        public boolean isFile() {
            return file;
        }

        public void setFile(boolean file) {
            this.file = file;
        }
    }


    public List<FileInfo> getInfo(String path, String pattern) {
        if (path == null) {
            return null;
        }

        Filter<String> filter = PatternFilterFactory.createFilter(pattern);
        return getInfo(new File(path), filter);
    }


    public List<FileInfo> getInfo(final File file, final Filter<String> filter) {

        File[] files = file.listFiles();
        if(files==null){
            return null;
        }

        return CollectionUtils.map(files, new CollectionUtils.Converter<File, FileInfo>() {
            @Override
            public FileInfo convert(File data) {
                String name = data.getName();
                if (filter.accept(name)) {
                    boolean file = data.isFile();
                    long lastModified = data.lastModified();
                    FileInfo info = new FileInfo();
                    info.setName(name);
                    info.setLastModified(lastModified);
                    info.setFile(file);
                    return info;
                }
                return null;

            }
        });

    }
}
